package blog;

import java.io.DataInputStream;
import java.io.IOException;

import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

import blog.db.*;
import blog.gui.SplashGui;
import blog.gui.VerifyUserGui;

public class Midlet extends MIDlet {
	
	private boolean paused;
	
	public Midlet()
	{
		paused = false;
		SysRuntime.midlet = this;
		SysRuntime.display = Display.getDisplay( this );
	}

	private void _destory()
	{
		//do some real destory actions, like close db etc.
		BlogAccountDB.closeDB();
		BlogEntryDB.closeDB();
		ShortCutDB.closeDB();
	}
	
	public void destroyApp(boolean arg0) {
		_destory();
		this.notifyDestroyed();
	}

	protected void pauseApp() {
		paused = true;
	}

	protected void startApp() throws MIDletStateChangeException {
		if ( paused )
		{
			//maybe not needed
			//SysRuntime.display.setCurrent(SysRuntime.guiManager.getCurScreen());
		}
		else
		{
			if ( verifyUser() )
			{
				SysRuntime.guiManager.show(new SplashGui());
			}
			else
			{
				SysRuntime.guiManager.show(new VerifyUserGui(VerifyUserGui.TYPE_EXIT));
			}
		}
	}
	
	private boolean verifyUser()
	{
		RecordStore rs = null;
		byte[] data;
		try {
			rs = RecordStore.openRecordStore(ConstString.DB_NAME_USER_VERIFY, true);
			if ( rs.getNumRecords( )==0 )
			{
				//new db
				data = "1".getBytes( );
				rs.addRecord( data, 0, data.length );
				/******add 10.27 start*******/
				BlogAccountDB.openDB( );
				BlogAccount account = new BlogAccount();
				account.setAccountName("Demo Account");
				account.setUserName("testblog");
				account.setPassword("testblog");
				account.setBlogType(BlogAccount.TYPE_WORDPRESS);
				account.setFullUrl("http://www.buzzermatrix.com/wordpress/xmlrpc.php");
				account.setBlogId("1");
				account.setBlogUrl("http://www.buzzermatrix.com/wordpress/");
				account.setChecked( true );
				BlogAccountDB.add( account );
				BlogAccountDB.closeDB( );				
				/******add 10.27 end*******/
				
				return true;
			}
			else
			{
				data = rs.getRecord(1);
				String tmp = new String( data );
				if ( tmp.equals("true user") )
				{
					SysRuntime.registedUser = true;
					return true;
				}
				else
				{
					int tmpInt = Integer.parseInt( tmp );
					if ( tmpInt<10 )
					{
						tmpInt++;
						data = ( ""+tmpInt ).getBytes( );
						rs.setRecord( 1, data, 0, data.length );
						return true;
					}
					else
					{
						return false;
					}
				}
			}
		} catch (Exception e) {
		}
		finally
		{
			if ( rs!=null )
			{
				try {
					rs.closeRecordStore();
				} catch (RecordStoreException e) {
				}
			}
		}
		return false;
	}

}